<template>
 <div v-if="homeData.loginedUserInfo!=undefined" style="min-height: calc(100vh);width: 100%;color: var(--color-neutral-10);">
  <div style="margin: 0 auto;max-width: 1940px;width: 90%;padding-top: 40px;padding-bottom: 40px;">
    <p style="font-size: 28px;font-weight: bold;color: var(--color-neutral-10);">账户</p>
    <div style="margin-top: 40px;">
      <div @click="data.showChangeAvatarForm = true" style="display: inline-block;position: relative;">
        <div id="avatar-wrapper" style="width: 100%;height: 100%;position: absolute;border-radius: 1000px;z-index: 1000;cursor: pointer;">

        </div>
        <v-avatar id="avatar" v-if="data.userInfo!=undefined" color="surface-variant" size="150" style="font-size: 54px;">
          <span v-if="data.userInfo.avatar==''">{{ func.getShortName(data.userInfo.name) }}</span>
          <div v-if="data.userInfo.avatar!=''"  style="width: 150px;height: 150px;display: inline-block;background-position: center;background-repeat: no-repeat;background-size: cover;"
            :style="{
              backgroundImage:'url(' + appData.serverURL + '/download/' + data.userInfo.avatar + ')'
            }"
          >
          </div>
        </v-avatar>
      </div>
      <p style="margin-top: 20px;">考生姓名：{{ homeData.loginedUserInfo.name }}<span style="text-decoration: underline;color: red;margin-left: 10px;cursor: pointer;" @click="()=>{
        localStorage.removeItem('loginedUserInfo')
        location.reload()
      }">退出登录</span></p>
      <p style="margin-top: 10px;">登录邮箱：{{ homeData.loginedUserInfo.email }}</p>
      <v-expansion-panels style="margin-top: 20px;border: 0 !important" variant="outlined">
        <v-expansion-panel
          title="个人信息"
          style="color: var(--color-neutral-10);background-color: var(--color-neutral-1);border: 0 !important"
        >
          <v-expansion-panel-text>
            
            <v-form>
              <v-container>

                <v-row>
                  <v-col>
                    <v-text-field
                      :disabled="data.isEditing==false"
                      v-model="data.userInfo.name"
                      label="姓名"
                      variant="outlined"
                    ></v-text-field>
                  </v-col>
                  <v-col>
                    <v-select
                      @click="()=>{
                        data.userInfo.subjectType = ''
                      }"
                      :items="data.provinces"
                      :disabled="data.isEditing==false"
                      v-model="data.userInfo.province"
                      label="省份"
                      variant="outlined"
                    ></v-select>
                  </v-col>
                  <v-col>
                    <v-select
                      @click="getCurrentProvinceSubjecttypes"
                      :items="data.subjectTypes"
                      :disabled="data.isEditing==false"
                      v-model="data.userInfo.subjectType"
                      label="选科类型"
                      variant="outlined"
                    ></v-select>
                  </v-col>
                </v-row>

                <v-row>
                  <v-col>
                    <v-text-field
                      :disabled="data.isEditing==false"
                      v-model="data.userInfo.score"
                      label="高考分数"
                      variant="outlined"
                    ></v-text-field>
                  </v-col>
                  <v-col>
                    <v-text-field
                      :disabled="data.isEditing==false"
                      v-model="data.userInfo.ranks"
                      label="高考位次"
                      variant="outlined"
                    ></v-text-field>
                  </v-col>
                  <v-col>
                    <v-select
                      :disabled="data.isEditing==false"
                      v-model="data.userInfo.isSMSR"
                      label="身体受限情况"
                      variant="outlined"
                      :items="['无','色盲','色弱','色盲且色弱']"
                      >
                    </v-select>
                  </v-col>
                </v-row>

                <div v-if="data.subjects!=undefined && data.userInfo.subjectType!='理科' && data.userInfo.subjectType!='文科'" style="padding: 10px 10px;border-radius: 5px;background-color: var(--color-neutral-2);margin-bottom: 20px;width: calc((100% - 48px)/3)">
                  <p style="font-weight: bold;margin-bottom: 5px">选科</p>
                  <div v-for="item in Object.keys(data.subjects)" style="display: inline-block;width: 33.3%;margin-bottom: 10px"
                    :style="{
                    display:isSubjectDisplay(item)==true?'inline-block':'none'
                    }"
                  >
                    <span>{{ getSubjectNameByLetters(item) }}</span><br>
                    <a-switch :disabled="data.isEditing==false" style="margin-top: 2px" v-model="data.subjects[item]"></a-switch>
                  </div>

<!--                  <a-checkbox-group>-->
<!--                    <a-checkbox :model-value="data.subjects[item]" :value="data.subjects[item]">{{ getSubjectNameByLetters(item) }}</a-checkbox>-->
<!--                  </a-checkbox-group>-->
                </div>

                <div style="padding: 10px 10px;border-radius: 5px;background-color: var(--color-neutral-2);margin-bottom: 20px;width: calc((100% - 48px)/3)">
                  <p style="font-weight: bold;margin-bottom: 5px">兴趣特长</p>
                  
                </div>

                <p v-if="data.warningText!=''" style="color: red;">{{ data.warningText }}</p>

                <div style="text-align: right;">
                  <v-btn v-if="data.isEditing==false" variant="text" @click="()=>{
                    data.isEditing = true
                  }">修改</v-btn>
                  <v-btn style="margin-left: 10px;" v-if="data.isEditing" variant="text" @click="()=>{
                    location.reload()
                    data.userInfo = JSON.parse(JSON.stringify(homeData.loginedUserInfo))
                    prepareUserInfo()
                    data.isEditing = false
                  }">取消</v-btn>
                  <v-btn style="margin-left: 10px;" v-if="data.isEditing" variant="text" @click="saveUserInfo">保存</v-btn>
                </div>

              </v-container>
            </v-form>
          </v-expansion-panel-text>
        </v-expansion-panel>
        <v-expansion-panel
          title="VIP特权"
          style="color: var(--color-neutral-10);background-color: var(--color-neutral-1);"
        >
          <v-expansion-panel-text>
            <div v-if="homeData.loginedUserInfo.isVIP==0">
              <p style="color: var(--color-neutral-10)">请输入序列号</p>
              <input placeholder="序列号" style="padding: 3px 3px;border-radius: 3px;background-color: var(--color-neutral-2);font-size: 14px;color: var(--color-neutral-10);margin-top: 10px;width: 100%;" v-model="data.input" />
              <p v-if="data.warningText2!=''" style="font-size: 14px;color: red">{{ data.warningText2 }}</p>
              <div style="text-align: right;margin-top: 15px">
                <button @click="async ()=>{
                  if(data.working==true)return
                  data.warningText2 = ''
                  if(data.input==''){
                    data.warningText2 = '无法激活，原因：未输入序列号'
                    data.working = false
                    return
                  }
                  data.working = true
                  let re = await tool.axiosPostWithCheckStatus(config.serverURL,'/user/activeVIPCard',{
                    mark:homeData.loginedUserInfo.mark,
                    token:homeData.token,
                    key:data.input
                  })
                  data.working = false
                  if(re.status==0){
                    data.warningText2 = '无法激活，原因：' + re.content
                    return
                  }
                  location.reload()
                }">激活</button>
              </div>
            </div>
            <p v-if="homeData.loginedUserInfo.isVIP==1" style="color: var(--color-neutral-10)">此账号已激活VIP</p>
          </v-expansion-panel-text>
        </v-expansion-panel>

        <v-expansion-panel
            title="修改登录密码"
            style="color: var(--color-neutral-10);background-color: var(--color-neutral-1);"
        >
          <v-expansion-panel-text>
            <div style="margin-top: 20px">
              <v-text-field
                  style="width: calc((100% - 48px) / 3);margin-right: 24px;display: inline-block"
                  v-model="data.changePassword.opassword"
                  label="原密码"
                  variant="outlined"
                  type="password"
                  :disabled="data.changePassword.isChanging"
              ></v-text-field>
              <v-text-field
                  style="width: calc((100% - 48px) / 3);margin-right: 24px;display: inline-block"
                  v-model="data.changePassword.nPassword"
                  label="新密码"
                  variant="outlined"
                  type="password"
                  :disabled="data.changePassword.isChanging"
              ></v-text-field>
              <v-text-field
                  style="width: calc((100% - 48px) / 3);display: inline-block"
                  v-model="data.changePassword.rnPassword"
                  label="重复新密码"
                  variant="outlined"
                  type="password"
                  :disabled="data.changePassword.isChanging"
              ></v-text-field>
              <p v-if="data.changePassword.warningText!=''" style="color: red;font-size: 14px">{{ data.changePassword.warningText }}</p>
              <div style="text-align: right;margin-top: 10px;">
                <button :disabled="data.changePassword.isChanging" @click="async ()=>{
                  if(data.changePassword.isChanging==true)return
                  data.changePassword.warningText = ''
                  if(data.changePassword.opassword==''){
                    data.changePassword.warningText = '请输入原密码'
                    return
                  }
                  if(data.changePassword.npassword==''){
                    data.changePassword.warningText = '请输入新密码'
                    return
                  }
                  if(data.changePassword.rnpassword==''){
                    data.changePassword.warningText = '请再次输入新密码'
                    return
                  }
                  if(tool.isVaildPasswordString(data.changePassword.nPassword)==false){
                    data.changePassword.warningText = '密码长度应不短于8位、不长于16位，由大小写字母和数字组成'
                    return
                  }
                  if(data.changePassword.nPassword!=data.changePassword.rnPassword){
                    data.changePassword.warningText = '两次输入的新密码不一致'
                    return
                  }
                  data.changePassword.isChanging = true
                  console.log(data.changePassword.opassword)
                  let re = await tool.axiosPostWithCheckStatus(config.serverURL,'/user/changePassword',{
                    token:homeData.token,
                    opassword:sha256(data.changePassword.opassword),
                    password:sha256(data.changePassword.nPassword),
                    mark:homeData.loginedUserInfo.mark
                  })
                  data.changePassword.isChanging = false
                  if(re.status==0){
                    data.changePassword.warningText = re.content
                    return
                  }
reLoginAfterChangingPassword()
                }">确认修改</button>
              </div>
            </div>
          </v-expansion-panel-text>
        </v-expansion-panel>

      </v-expansion-panels>
    </div>
  </div>
  <div v-if="data.showChangeAvatarForm" style="width: calc(100vw - 70px);height: 100vh;position: fixed;top: 0;z-index: 2000;background-color: rgba(25,25,25,0.1);padding-left: calc(50vw - 35px);padding-top: 50vh;right: 0;">
    <div style="transform: translate(-50%,-50%);box-shadow: 0 4px 10px rgba(0,0,0,0.1);border-radius: 10px;display: inline-block;background-color: var(--color-neutral-1);
      position: relative;
      width: calc(100vw - 70px);height: 100vh;
      max-height: 400px;
      max-width: 400px;
    ">
      <div style="width: 100%;position: relative;padding: 20px 20px;padding-bottom: 10px;">
        <span style="font-size: 18px;font-weight: bold;">修改头像</span>
        <svg @click="()=>{
          data.showChangeAvatarForm = false
        }" style="float: right;cursor: pointer;" width="24" height="24" viewBox="0 0 48 48" fill="currentColor"><path fill-rule="evenodd" clip-rule="evenodd" d="M23.886 20.957L37.32 7.522a1 1 0 011.414 0l1.414 1.414a1 1 0 010 1.415L26.714 23.786 40.149 37.22a1 1 0 010 1.414l-1.414 1.414a1 1 0 01-1.414 0L23.886 26.614 10.45 40.049a1 1 0 01-1.415 0l-1.414-1.414a1 1 0 010-1.414l13.435-13.435L7.622 10.35a1 1 0 010-1.415l1.414-1.414a1 1 0 011.415 0l13.435 13.435z" fill="currentColor"/></svg>
      </div>
      <div style="width: 100%;height: calc(100% - 10px);overflow-y: scroll;text-align: center;">
        <button style="margin-top:10px"
          @click="deleteAvatar"
          v-if="data.userInfo.avatar!=''"
        >删除头像</button>
        <br>
        <button style="margin-top:10px"
          @click="openAvatar"
          v-if="data.userInfo.avatar!=''"
        >查看头像</button>
        <br>
        <button style="margin-top:10px" @click="postSelectedFileToUrl">选择文件</button>
      </div>
    </div>
  </div>
 </div>
</template>

<script>
import router from '@/router';
import tool, { getShortName } from '@/utlis/tool';
import config from '@/config';
import axios from 'axios';
import vip from '../../components/vip.vue'
import sha256 from "js-sha256";

export default{
  computed:{
    sha256() {
      return sha256
    },
    localStorage(){
      return localStorage
    },
    location(){
      return location
    },
    tool(){
      return tool
    },
    config(){
      return config
    }
  },
  components:{
    vip
  },
  data(){
    return{
      data:{
        userInfo:undefined,
        isEditing:undefined,
        warningText:'',
        provinceSubjects:undefined,
        provinces:[],
        subjectTypes:[],
        showChangeAvatarForm:false,
        subjects:undefined,
        input:'',
        working:false,
        warningText2:'',
        changePassword:{
          opassword:'',
          nPassword:'',
          rnPassword:'',
          warningText:'',
          isChanging:false,
        }
      },
      func:{
        getShortName:undefined
      }
    }
  },
  async mounted(){
    this.func.getShortName = tool.getShortName

    if(this.homeData.loginedUserInfo==undefined){
      router.push('/')
      return
    }
    this.prepareUserInfo()
    await this.getProvinceSubjects()
    this.data.isEditing = false
  },
  methods:{
    reLoginAfterChangingPassword(){
      alert('修改成功，请重新登录')
      localStorage.removeItem('loginedUserInfo')
      location.reload()
    },
    isSubjectDisplay(name){
      switch (name) {
        case 'wl':
          if(this.data.userInfo.subjectType=='物理类' || this.data.userInfo.subjectType=='历史类'){
            return false
          }
          if(this.data.userInfo.subjectType=='文科'){
            return false
          }
      return true
        case 'hx':
          if(this.data.userInfo.subjectType=='文科'){
            return false
          }
      return true
        case 'sw':
          if(this.data.userInfo.subjectType=='文科'){
            return false
          }
      return true
        case 'zz':
          if(this.data.userInfo.subjectType=='理科'){
            return false
          }
      return true
        case 'ls':
          if(this.data.userInfo.subjectType=='物理类' || this.data.userInfo.subjectType=='历史类'){
            return false
          }
          if(this.data.userInfo.subjectType=='理科'){
            return false
          }
      return true
        case 'dl':
          if(this.data.userInfo.subjectType=='理科'){
            return false
          }
      return true
      }
      return true
    },
    getSubjectNameByLetters(letters){
      switch (letters) {
        case 'wl':return '物理';
        case 'hx':return '化学';
        case 'sw':return '生物';
        case 'zz':return '政治';
        case 'ls':return '历史';
        case 'dl':return '地理';
      }
    },
    openAvatar(){
      window.open(this.appData.serverURL + '/download/' + this.data.userInfo.avatar)
    },
    async deleteAvatar(){
      await tool.axiosPostWithCheckStatus(config.serverURL,'/delete',{
        name:this.data.userInfo.avatar
      })      
      this.data.userInfo.avatar = ''
      this.saveUserInfo()
      this.data.showChangeAvatarForm = false
    },
    async postSelectedFileToUrl() {  
      const fileInput = document.createElement('input');  
      fileInput.type = 'file';  
      fileInput.addEventListener('change', (e) => {  
        const file = e.target.files[0];
        if (file) {  
          const formData = new FormData();  
          formData.append('file', file);  
          axios.post(config.serverURL + '/upload', formData, {  
            headers: {  
              'Content-Type': 'multipart/form-data'  
            }  
          }).then(async response => {  
            let fn = response.data.results

            if(this.data.userInfo.avatar!=''){
              await tool.axiosPostWithCheckStatus(config.serverURL,'/delete',{
                name:this.data.userInfo.avatar
              })
            }
            this.data.userInfo.avatar = fn
            await this.saveUserInfo()
            this.data.showChangeAvatarForm = false

          }).catch(error => {  
            
          });  
        } else {  
          
        }  
      });  
      fileInput.click();  
    },
    async getProvinceSubjects(){
      let re = await tool.axiosPostWithCheckStatus(config.serverURL,'/provincesAndSubjects',{})
      this.data.provinceSubjects = re.results
      let re0 = []
      for(let i=0;i<this.data.provinceSubjects.length;i++){
        re0.push(this.data.provinceSubjects[i].name)
      }
      this.data.provinces = re0
      this.getCurrentProvinceSubjecttypes()
    },
    getCurrentProvinceSubjecttypes(){
      let re1 = []
      for(let i=0;i<this.data.provinceSubjects.length;i++){
        if(this.data.provinceSubjects[i].name==this.data.userInfo.province){
          for(let i1=0;i1<this.data.provinceSubjects[i].type.length;i1++){
            re1.push(this.data.provinceSubjects[i].type[i1].name)
          }
          this.data.subjectTypes = re1
          break
        }
      }
    },
    async saveUserInfo(){
      this.data.warningText=''
      if(parseInt(this.data.userInfo.score)==null){
        this.data.warningText='请输入正确的高考分数'
        return
      }
      if(parseInt(this.data.userInfo.score)<0 || parseInt(this.data.userInfo.score)>750){
        this.data.warningText='请输入正确的高考分数'
        return
      }
      if(parseInt(this.data.userInfo.ranks)==null){
        this.data.warningText='请输入正确的高考位次'
        return
      }
      if(parseInt(this.data.userInfo.ranks)<0){
        this.data.warningText='请输入正确的高考位次'
        return
      }
      if(this.data.userInfo.name==''){
        this.data.warningText='请输入姓名'
        return
      }
      if(this.data.userInfo.subjectType==''){
        this.data.warningText='请选择选科类型'
        return
      }

      let currentSubjectType = this.data.userInfo.subjectType
      if(currentSubjectType=='综合' || currentSubjectType=='本科' || currentSubjectType=='专科'){
      let num = 0
      for(let i=0;i<Object.keys(this.data.subjects).length;i++){
        if(this.data.subjects[Object.keys(this.data.subjects)[i]]==true){
          num+=1
        }
      }
        if(num!=3){
          this.data.warningText = '请选择3个科目'
          return
        }
      }
      if(currentSubjectType=='物理类' || currentSubjectType=='历史类'){
      let num = 0
      for(let i=0;i<Object.keys(this.data.subjects).length;i++){
        if(Object.keys(this.data.subjects)[i]=='wl' || Object.keys(this.data.subjects)[i]=='ls')continue
        if(this.data.subjects[Object.keys(this.data.subjects)[i]]==true){
          num+=1
        }
      }
        if(num!=2){
          this.data.warningText = '请选择2个科目'
          return
        }
      }
      if(currentSubjectType=='理科'){
        this.data.subjects.wl = true
        this.data.subjects.hx = true
        this.data.subjects.sw = true
        this.data.subjects.zz = false
        this.data.subjects.ls = false
        this.data.subjects.dl = false
      }
      if(currentSubjectType=='文科'){
        this.data.subjects.zz = true
        this.data.subjects.ls = true
        this.data.subjects.dl = true
        this.data.subjects.wl = false
        this.data.subjects.hx = false
        this.data.subjects.sw = false
      }
      if(currentSubjectType=='物理类'){
        this.data.subjects.wl = true
      }
      if(currentSubjectType=='历史类'){
        this.data.subjects.ls = true
      }

      this.data.userInfo.score = parseInt(this.data.userInfo.score)
      this.data.userInfo.ranks = parseInt(this.data.userInfo.ranks)
      this.data.userInfo.subjects = JSON.stringify(this.data.subjects)
      switch (this.data.userInfo.isSMSR) {
        case '色盲且色弱':
          this.data.userInfo.isSM = 1
          this.data.userInfo.isSR = 1
          break;
        case '色盲':
          this.data.userInfo.isSM = 1
          this.data.userInfo.isSR = 0
          break;
        case '色弱':
          this.data.userInfo.isSM = 0
          this.data.userInfo.isSR = 1
          break;
        case '无':
          this.data.userInfo.isSM = 0
          this.data.userInfo.isSR = 0
          break;
      }
      let re = await tool.axiosPostWithCheckStatus(config.serverURL,'/user/changeInfo',{
        userInfo:this.data.userInfo,
        token:this.homeData.token
      })
      this.data.isEditing = false
      location.reload()
    },
    prepareUserInfo(){
      this.data.userInfo = this.homeData.loginedUserInfo
      try {
        this.data.subjects = JSON.parse(this.data.userInfo.subjects)
        this.data.subjects = JSON.parse(this.data.subjects)
        this.data.subjects = JSON.parse(this.data.subjects)
      }catch (e) {

      }
      if(this.data.userInfo.isSM==1 && this.data.userInfo.isSR==1){
        this.data.userInfo.isSMSR = '色盲且色弱'
      }
      if(this.data.userInfo.isSM==0 && this.data.userInfo.isSR==1){
        this.data.userInfo.isSMSR = '色弱'
      }
      if(this.data.userInfo.isSM==1 && this.data.userInfo.isSR==0){
        this.data.userInfo.isSMSR = '色盲'
      }
      if(this.data.userInfo.isSM==0 && this.data.userInfo.isSR==0){
        this.data.userInfo.isSMSR = '无'
      }
    }
  },
  props:{
    appData:undefined,
    homeData:undefined
  },
}
</script>

<style scoped>

#avatar-wrapper{
  border: 4px solid transparent;
}

#avatar-wrapper:hover{
  border: 4px solid rgb(0,120,215);
}

button{
  border: 1px solid rgba(128,128,128,0.2) !important;
}

</style>